package src.server;

import src.mysql.ScoreSqlHelper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author CsCN
 * 比赛线程
 */
public class MatchThread extends Thread {

    private final SocketHelper player1;
    private final SocketHelper player2;
    private Boolean oneFailed = false;
    private final ScoreSqlHelper.Difficulty difficulty;

    public MatchThread(SocketHelper player1, SocketHelper player2, ScoreSqlHelper.Difficulty difficulty) {
        this.player1 = player1;
        this.player2 = player2;
        this.difficulty = difficulty;
    }

    @Override
    public void run() {
        // 开始游戏
        player1.sendString("start");
        player2.sendString("start");
        Thread thread1 = new Thread(() -> recvAndSend(player1, player2));
        Thread thread2 = new Thread(() -> recvAndSend(player2, player1));
        thread1.start();
        thread2.start();
        try {
            thread1.join();
            thread2.join();
            System.out.println("Game Over");
            player1.close();
            player2.close();
        } catch (InterruptedException | IOException e) {
//            e.printStackTrace();
        }
    }

    public void recvAndSend(SocketHelper recv, SocketHelper send) {
        int score = 0;
        while (true) {
            String str = recv.recvString();
            // 如果当前用户游戏结束, 处理后事
            if (str.equals("GG")) {
                // 让另一个线程不要再接收数据了, 这里即使线程竞争也无所谓, 因为两个线程都会退出
                oneFailed = true;
                // 通知另一方
                send.sendString("GG");
                // 获取时间
                Date day = new Date();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                // 添加记录到数据库中
                ScoreServer.scoreSqlHelper.addScore(recv.tag, score, df.format(day), difficulty);
                break;
            }
            score = Integer.parseInt(str);
            if (!oneFailed) {
                send.sendString(Integer.toString(score));
            }
            try {
                Thread.sleep(500);
            } catch (Exception e) {
//                e.printStackTrace();
            }
        }

        while (true) {
            send.sendString(Integer.toString(score));
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }

    }
}
